package com.demo.web;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
/**
 * 图片验证码生成服务
 *
 * Created by liushaokang on 2017/3/14.
 */

@Controller
@RequestMapping("admin/code")
public class CaptchaController {
    private Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    @Autowired
    private Producer captchaProducer = null;

    @RequestMapping(value = "captcha-image")
    public ResponseEntity<byte[]> getKaptchaImage(HttpServletRequest request) {
        HttpHeaders headers = new HttpHeaders();
        headers.setPragma("no-cache");
        headers.setExpires(0);
        headers.set("Cache-Control", "no-store, no-cache, must-revalidate");
        headers.setContentType(MediaType.IMAGE_JPEG);

        String capText = captchaProducer.createText();
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

        logger.info("验证码: " + capText);

        BufferedImage bi = captchaProducer.createImage(capText);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(bi, "jpg", out);

            return new ResponseEntity<>(out.toByteArray(), headers, HttpStatus.OK);
        } catch (IOException e) {
            logger.error(e.getMessage());
        }

        return null;
    }
}
